package com.zheng.controller;


import com.zheng.Utils.UUIDutils;
import com.zheng.pojo.Books;
import com.zheng.service.BookService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/book")
public class BooksController {

    @Autowired
    BookService bookService;

    //查询所有的书籍数量
    @GetMapping("/findAllCount")
    public List<Books> findCount(){
        return bookService.findAllCount();
    }

    //查询所有的书籍信息
    @GetMapping("/findAll/{page}/{size}")
    public Map<String,Object> findAll(@PathVariable("page") Integer Page,@PathVariable("size") Integer size) {

        //准备数据 通过这两个参数，可以算出start   计算方法 start=size(page-1)
        int currentPage = Page;//当前是第几页
        int pageSize = size; //页面大小

        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",(currentPage-1)*pageSize);
        map.put("pageSize",pageSize);
        List<Books> booklist =  bookService.queryBookList(map);
        HashMap<String,Object> result = new HashMap<>();
        Long totals = bookService.findTotals();
        result.put("books",booklist);
        result.put("totals",totals);
        return result;


    }

    @PostMapping("/save")
    public String save(@RequestBody  Books books){
//        String id = UUIDutils.getUUID();
//        books.setBookId(id);
      int i=  bookService.addBook(books);

      if(i > 0){
          return "success";
      }else{
          return "error";
      }

    }

    //查询某一本书籍
    @GetMapping("/findOneBook/{id}")
    public Map<String,Object> findOneBook(@PathVariable("id") Integer id){
        Books books = bookService.findBookById(id);
        HashMap<String,Object> result = new HashMap<>();
        result.put("books",books);
        return result;
    }

    @PutMapping("/update")
    public String update(@RequestBody  Books books){

        int i=  bookService.updateBook(books);

        if(i > 0){
            return "success";
        }else{
            return "error";
        }

    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteBook(@PathVariable("id") Integer id){
        bookService.deleteBook(id);

    }



}
